package com.jml.循环引用006;


import com.jml.循环引用006.config.MyConfig;
import com.jml.循环引用006.config.MyConfig001;
import com.jml.循环引用006.config.MyConfig002;
import com.jml.循环引用006.service.AService;
import com.jml.循环引用006.service.BService;
import java.util.HashMap;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;



public class SpringApp {
    public static void main(String[] args) {
       
       AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        AService aSerivce = applicationContext.getBean("AService", AService.class);
        BService bSerivce = applicationContext.getBean("BService", BService.class);
       //----------------------------------------------------------------------------------------------------------------------------
       /*
        //多例循环引用报错
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig001.class);
        AService aSerivce = applicationContext.getBean("AService", AService.class);
        BService bSerivce = applicationContext.getBean("BService", BService.class);
        */
       //----------------------------------------------------------------------------------------------------------------------------
        /*
        //多例：其中一个改为手动注入
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig002.class);
        com.jml.循环引用006.service002.AService aSerivce = applicationContext.getBean("AService", com.jml.循环引用006.service002.AService.class);
        com.jml.循环引用006.service002.BService bSerivce = applicationContext.getBean("BService", com.jml.循环引用006.service002.BService.class);
        aSerivce.setbService(bSerivce);
        bSerivce.setaService(aSerivce);
        */
        // 循环引用异常 找不到对象
        /**
         * 思考问题？ 如果我们的项目对象必须要是多例？ 而且必须要循环引用  明确的指定引用那个对象
         */
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (int i = 0; i < beanDefinitionNames.length; i++) {
            System.out.println(beanDefinitionNames[i]);
        }
        /**
         * spring中单例的情况下 实际上已经帮助我们解决好了这样循环依赖问题
         *
         * 分析Spring单例 循环依赖的问题底层是如何解决的？
         * 单例对象在什么时候被创建。 IOC容器被加载的时候创建  多例子的情况下 是在调用的时候创建
         */
        /*
        // 缓存我们的婴儿对象
        HashMap<String, Object> stringObjectHashMap = new HashMap<String, Object>();
        stringObjectHashMap.put("aService", new AService());
        stringObjectHashMap.put("bService", new BService());
        // 3.从三级缓存中查询到赋值
        AService aService = (AService) stringObjectHashMap.get("aService");
        BService bService = (BService) stringObjectHashMap.get("bService");
        aService.bService = bService;
        // Java的引用传递
        bService.aService = aService;
        */
    }
}
